package Servlet;

import java.io.IOException;
import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import datebase.DbUtil;
import datebase.Workclass;
import datebase.WorkclassDaoIplm;
import datebase.Works;
import datebase.WorksDaoIplm;



public class insert_goodServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public insert_goodServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		Workclass wc = null;
		List<Works> wklist = null;
		int work_num = Integer.parseInt(request.getParameter("work_num"));
		String work_firstclass = request.getParameter("first_class");
		String work_secondclass = request.getParameter("second_class");
		wc = getworkclass(work_firstclass,work_secondclass);
		System.out.println(work_firstclass+":"+work_secondclass+":"+wc.getWork_class_id());
		String workstatus = request.getParameter("work_status");
		String workname = request.getParameter("work_name");
		String workdes = request.getParameter("work_description");
		String workprice = request.getParameter("work_price");
		String workimg = request.getParameter("work_image");	
		try {
		    if (wc == null) {
		        throw new Exception("作品分类信息为空，请检查一级分类和二级分类参数");
		    }
		    
		    Integer workClassId = wc.getWork_class_id();
		    if (workClassId == null) {
		        throw new Exception("作品分类ID为空");
		    }
		    
		    Works wk = new Works(workstatus, workname, workdes, workimg, workprice, work_num, wc);
			System.out.println(wk.getWork_class().getWork_class_id());
		    Connection con  = null;   
			WorksDaoIplm wkdi = new WorksDaoIplm();
			con = DbUtil.getCon();
			wkdi.insert(con, wk);
			wklist = wkdi.serachAll(con); 
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		request.getSession().setAttribute("wklist", wklist);
		response.sendRedirect("modify_good_status.jsp");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	public static Workclass getworkclass(String first_class,String second_class) {
		WorkclassDaoIplm wcdi = new WorkclassDaoIplm();
		Workclass wc = null;
		Connection con  = null;
		try {
			con = DbUtil.getCon();
			wc=wcdi.serach(con,first_class, second_class);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		return wc;
	}
}
